package com.woniuxy.controller;

import com.woniuxy.utils.MinioUtil;
import com.woniuxy.utils.ResponseResult;
import io.minio.*;
import io.minio.errors.MinioException;
import io.minio.http.Method;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.List;

@RestController
@RequestMapping("/life/minio")
public class MinioController {

    private final MinioUtil minioUtil;

    private final MinioClient minioClient;

    public MinioController(MinioUtil minioUtil, MinioClient minioClient) {
        this.minioUtil = minioUtil;
        this.minioClient = minioClient;
    }

    // 创建存储桶
    @PostMapping("/bucket")
    public ResponseEntity<String> createBucket(@RequestParam String bucketName) {
        try {
            minioUtil.createBucket(bucketName);
            return ResponseEntity.ok("存储桶创建成功: " + bucketName);
        } catch (MinioException | IOException e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("创建失败: " + e.getMessage());
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        } catch (InvalidKeyException e) {
            throw new RuntimeException(e);
        }
    }

    @PostMapping("/upload")
    public ResponseResult<String> upload(@RequestParam("file") MultipartFile file) {
        String fileName = file.getOriginalFilename();
        long size = file.getSize();
        try {
            InputStream inputStream = file.getInputStream();
            //通过stream流来上传图片
            ObjectWriteResponse oss = minioClient.putObject(
                    PutObjectArgs.builder()
                            .stream(inputStream,size,-1l)
                            .object(fileName)
                            .bucket("java113")
                            .build()
            );
            //获取文件的访问路径 share分享的url地址
            String url = minioClient.getPresignedObjectUrl(
                    GetPresignedObjectUrlArgs.builder()
                            .method(Method.GET)
                            .bucket("java113")
                            .object(fileName)
                            .build());
            System.out.println("传出的url地址"+url);
            return  ResponseResult.success(url);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    // 上传文件
//    @PostMapping("/upload")
//    public ResponseResult<String> uploadFile(
//            @RequestParam("bucketName") String bucketName,
//            @RequestParam("file") MultipartFile file
//    ) throws Exception {
//        try {
//            // 检查存储桶是否存在，不存在则创建
//            if (!minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build())) {
//                createBucket(bucketName);
//            }
//
//            String objectName = minioUtil.uploadFile(bucketName, file);
////            return ResponseEntity.ok(objectName);
//            ResponseResult<String> success = ResponseResult.success(objectName);
//
//            return success;
//        } catch (MinioException | IOException e) {
////            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
////                    .body("上传失败: " + e.getMessage());
//            return ResponseResult.fail(500, "上传失败: " + e.getMessage());
//        } catch (Exception e) {
//            throw new Exception(e);
//        }
//    }

    // 下载文件
    @GetMapping("/download")
    public ResponseEntity<byte[]> downloadFile(
            @RequestParam String bucketName,
            @RequestParam String objectName
    ) {
        try {
            byte[] data = minioUtil.downloadFile(bucketName, objectName);
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            headers.setContentDispositionFormData("attachment", objectName);
            return new ResponseEntity<>(data, headers, HttpStatus.OK);
        } catch (MinioException | IOException e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(null);
        }
    }

    // 删除文件
    @DeleteMapping("/delete")
    public ResponseEntity<String> deleteFile(
            @RequestParam String bucketName,
            @RequestParam String objectName
    ) {
        try {
            minioUtil.deleteFile(bucketName, objectName);
            return ResponseEntity.ok("文件删除成功: " + objectName);
        } catch (MinioException | IOException e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("删除失败: " + e.getMessage());
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        } catch (InvalidKeyException e) {
            throw new RuntimeException(e);
        }
    }

    // 列举存储桶
    @GetMapping("/buckets")
    public ResponseEntity<List<String>> listBuckets() {
        try {
            List<String> buckets = minioUtil.listBuckets();
            return ResponseEntity.ok(buckets);
        } catch (MinioException | IOException e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(null);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        } catch (InvalidKeyException e) {
            throw new RuntimeException(e);
        }
    }

    // 列举对象
    @GetMapping("/objects")
    public ResponseEntity<List<String>> listObjects(@RequestParam String bucketName) {
        try {
            List<String> objects = minioUtil.listObjects(bucketName);
            return ResponseEntity.ok(objects);
        } catch (MinioException | IOException e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(null);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        } catch (InvalidKeyException e) {
            throw new RuntimeException(e);
        }
    }
}